const jwt = require('jsonwebtoken')
const SECRET_KEY = 'leyouhui-010515-project'

// 生成token
const generateToken = (user, key) => {
  if (key === 'front') {
    return jwt.sign({ user_id: user }, SECRET_KEY, { expiresIn: '5h' })
  } else {
    return jwt.sign({ username: user }, SECRET_KEY, { expiresIn: '5h' })
  }
}

// 验证token
const checkToken = (token) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, SECRET_KEY, (err, decoded) => {
      if (err) {
        reject(err)
      } else {
        resolve(decoded)
      }
    })
  })
}

module.exports = {
  generateToken,
  checkToken
}